package com.itboye.jinpuyiyuan.activity.me;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.PersonBean;
import com.itboye.jinpuyiyuan.bean.UploadImageBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.uploadmultipleimage.UploadImageUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.CameraPopupWindow;
import com.itboye.jinpuyiyuan.widget.CircleImageView;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.ImageCompress;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2017/12/15 0015.
 *
 */

public class PersonInfoActivity extends BaseActivity implements Observer ,UploadImageUtils.UploadResult {
    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft,toobar;

    private CircleImageView imgHead;
    private TextView saveTv;
    private EditText produceEt,nicknameEt;
    private TextView sexEt;
    private LinearLayout sexSelectLl;
    private PopupWindow sexPop;
    private BranchAddressPresenter presenter,presenter1;
    private String uid;
    private String nick,produce;//昵称，性别，简介
    private int online_status;//在线状态
    private int sex;

    private Bitmap headBitmap;//头像
    private String imgId;//头像
    private RelativeLayout user_image_layout;
    private String logoUrl;
    private CameraPopupWindow cameraPopupWindow;
    // 使用相机拍照
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
    private static  final int CAMARE_IMAGE_ACTIVITY_REQUEST_CODE =112;
    private static final int WRITE_IMAGE_ACTIVITY_REQUEST_CODE =113;
    // 获取日期格式器对象
    private String picture_name;
    private String fileName;
    private String localSelectPath;
    public static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择

    public static final int IMAGE_COMPLETE = 6; // 结果

    private ProgressDialog mProgressDialog;


    private String logoPath;

    private View.OnClickListener onclicklister = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.open_camera:
                    /**
                     * 打开照相机
                     */

                   if ( ActivityCompat.checkSelfPermission(PersonInfoActivity.this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)!=0){
                       ActivityCompat.requestPermissions(PersonInfoActivity.this,
                               new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                   }else if (  ActivityCompat.checkSelfPermission(PersonInfoActivity.this,
                           Manifest.permission.CAMERA)!=0){
                           ActivityCompat.requestPermissions(PersonInfoActivity.this,
                                   new String[]{Manifest.permission.CAMERA}, CAMARE_IMAGE_ACTIVITY_REQUEST_CODE);
                   }else if (  ActivityCompat.checkSelfPermission(PersonInfoActivity.this,
                           Manifest.permission.WRITE_EXTERNAL_STORAGE)!=0){
                       ActivityCompat.requestPermissions(PersonInfoActivity.this,
                               new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_IMAGE_ACTIVITY_REQUEST_CODE);
                   }else {
                           saveFullImage();
                   }

//                    String state = Environment.getExternalStorageState();
//                    if (state.equals(Environment.MEDIA_MOUNTED)) {
//                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        startActivityForResult(intent,
//                                CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
//                    } else {
//                        MAlert.alert("请确认是否插入SD卡");
//                    }
                    break;
                case R.id.pick_image:
                    // new PhotoSelectFragment(new PhotoSelect(),
                    // 6 - imgContainer.getChildCount() + 1).show(
                    // getSupportFragmentManager(), null);
                    // 激活系统图库，选择一张图片
                    Intent intent = new Intent(PersonInfoActivity.this, HeadPresActivity.class);
                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
                    startActivityForResult(intent,PHOTO_REQUEST_GALLERY);
                    break;

                default:
                    break;
            }
        }

    };
    Uri mOutPutFileUri;
    private void saveFullImage(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//文件夹aaaa
        String path = Environment.getExternalStorageDirectory().toString()+"/aaaa";
        File path1 = new File(path);
        if(!path1.exists()){
            path1.mkdirs();
        }

        File file = new File(path1,System.currentTimeMillis()+".jpg");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            mOutPutFileUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    FileProvider.getUriForFile(this,"jinpuyiyuan.fileprovider", file));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
        }else {
            mOutPutFileUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,mOutPutFileUri);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        }
        startActivityForResult(intent,1);


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }else {
                MAlert.alert("请手动添加读权限");
            }

        }
        if (requestCode == CAMARE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }else {
                MAlert.alert("请手动相机存储权限");
            }
        }
        if (requestCode == WRITE_IMAGE_ACTIVITY_REQUEST_CODE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }else {
                MAlert.alert("请手动相机写权限");
            }
        }

        if (  ActivityCompat.checkSelfPermission(PersonInfoActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)!=0){
            ActivityCompat.requestPermissions(PersonInfoActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }else if (  ActivityCompat.checkSelfPermission(PersonInfoActivity.this,
                Manifest.permission.CAMERA)!=0){
            ActivityCompat.requestPermissions(PersonInfoActivity.this,
                    new String[]{Manifest.permission.CAMERA}, CAMARE_IMAGE_ACTIVITY_REQUEST_CODE);
        }else if (  ActivityCompat.checkSelfPermission(PersonInfoActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)!=0){
            ActivityCompat.requestPermissions(PersonInfoActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_IMAGE_ACTIVITY_REQUEST_CODE);
        }else {
            saveFullImage();
        }


        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_personinfo);
        rightImg.setVisibility(View.GONE);
        leftTv.setVisibility(View.GONE);
        tvTitle.setText("个人资料修改");

        presenter=new BranchAddressPresenter(this);
        presenter1=new BranchAddressPresenter(this);


        logoUrl= (String) SPUtils.get(getApplication(),null,"personLogo","");
        online_status= (int) SPUtils.get(getApplication(),null,Const.ONLINE_STATUS,0);
        uid=(String) SPUtils.get(getApplication(),null,Const.UID,"");
        nick= (String) SPUtils.get(getApplication(),null,Const.NICK,"");
        sex= (int) SPUtils.get(getApplication(),null,Const.SEX,0);
        produce= (String) SPUtils.get(getApplication(),null,Const.SIGN,"");

        sexEt.setText(getSex(sex));

        if (nick!=null&&!nick.equals("")){
           nicknameEt.setText(nick);
           nicknameEt.setSelection(nick.length());
        }

        if (!produce.equals("")){
            produceEt.setText(produce);
            produceEt.setSelection(produce.length());
        }
        nicknameEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditor(nicknameEt)){ //edittext 有内容且光标在首位时不可编辑，否则可编辑

                    InputMethodManager imm = (InputMethodManager) nicknameEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(nicknameEt, 0);

                }else {
                    InputMethodManager imm = ((InputMethodManager) nicknameEt.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE));
                    imm.hideSoftInputFromWindow(nicknameEt.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });


        if (logoUrl==null||logoUrl.equals("")){
                    Thread thread= new Thread() {
            @Override
            public void run() {
                headBitmap=returnBitmap(Const.DoctorImg+uid);

                if (headBitmap==null){
                  runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgHead.setImageDrawable(getResources().getDrawable(R.drawable.login_logo));
                        }
                    });

                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgHead.setImageBitmap(headBitmap);
                        }
                    });
                }

            }
        };
        thread.start();

            return;
        }else {
            Bitmap bm = BitmapFactory.decodeFile(logoUrl);
            imgHead.setImageBitmap(bm);
        }

//        imgHead.setBackgroundDrawable(getResources().getDrawable(0));
//        Glide.with(this).load(Const.IMAGE_HEAD+uid).into(imgHead);

    }


    // 判断edittext文本是否可编辑  true 可以 false 不可以
    public boolean isEditor(EditText et){
        if (et.getText().length()>0){
            if (et.getSelectionStart()==0){

                return false;
            }

        }
        return true;
    }
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.rlLeft:
            case R.id.leftImg:
                this.finish();
                break;
            case R.id.user_image_layout:
            case R.id.imgHead:
                cameraPopupWindow = new CameraPopupWindow(
                        PersonInfoActivity.this, onclicklister);
                cameraPopupWindow.showAtLocation(view, Gravity.BOTTOM
                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
                //性别选择
            case R.id.sexSelectLl:
            case R.id.sexEt:
                showSexPop();

                break;

            case R.id.saveTv:
                imgHead.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(imgHead.getDrawingCache());

                if ("".equals(nicknameEt.getText().toString())
                        ||"".equals(sexEt.getText().toString())
                        ||produceEt.getText().toString().equals("")){
                    MAlert.alert("信息未填写完整，请填写完整");
                }else if (nick.equals(nicknameEt.getText().toString())
                        &&getSex(sex).equals(sexEt.getText().toString())
                        &&produce.equals(produceEt.getText().toString())
                        &&headBitmap==bitmap){

                   MAlert.alert("请修改后再提交");

                }else {
                    presenter.updateUserProfile(uid,nicknameEt.getText().toString(),produceEt.getText().toString(),getStringSex(sexEt.getText().toString()),"","",online_status);

                }
                imgHead.setDrawingCacheEnabled(false);

                break;

        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            Uri imageUri = null;
            if (data != null) {
                if (data.hasExtra("data")) {
                    Bitmap thunbnail = data.getParcelableExtra("data");
//                    imgHead.setImageBitmap(thunbnail);
//处理缩略图
                }
            } else {
//处理mOutPutFileUri中的完整图像
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                    logoPath=mOutPutFileUri.getPath();
                    Bitmap bitmap = BitmapFactory.decodeFile(ImageCompress.compress(logoPath));
                    imgHead.setImageBitmap(bitmap);

                    toUpImg(new File(mOutPutFileUri.getPath()));
                }else {
                    logoPath=mOutPutFileUri.getPath();
                    Bitmap bitmap = BitmapFactory.decodeFile(ImageCompress.compress(logoPath));
                    imgHead.setImageBitmap(bitmap);

                    toUpImg(new File(mOutPutFileUri.getPath()));
                }


            }



//        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
//                && resultCode == RESULT_OK) {
//            String sdStatus = Environment.getExternalStorageState();
//
//            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
//                return;
//            }
//
//            picture_name = android.text.format.DateFormat.format(
//                    "yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
//                    + ".jpg";
//            Bundle bundle = data.getExtras();
//            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
//            File file = new File("/sdcard/Image/");
//            file.mkdirs();// 创建文件夹
//            fileName = "/sdcard/Image/" + picture_name;
//            File file1 = new File(fileName);
//            toUpImg(file1);


//                FileOutputStream b = null;
//                try {
//
//                    if (b == null) {
//
//                        b = new FileOutputStream(fileName);
//                        Log.d("fileOutputStreams", b + "");
//
//                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
//
//                        Log.d("fileOutputStream", b + "");
//    //                    HeadUrl.onImage(fileName, imgHead);
//                        Bitmap bm = BitmapFactory.decodeFile(fileName);
//                        SPUtils.put(getApplication(),null,"personLogo",fileName);
//
//                        imgHead.setImageBitmap(bm);
//
//
//                    }
//
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                } finally {
//                    try {
//                        b.flush();
//                        b.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//            UploadImage.getInstance().execute(fileName, this);
           cameraPopupWindow.dismiss();

        } else if (requestCode == PHOTO_REQUEST_GALLERY && resultCode == PHOTO_REQUEST_GALLERY) {
            logoPath = data.getStringExtra("path");

            Bitmap bitmap = BitmapFactory.decodeFile(ImageCompress.compress(logoPath));
            imgHead.setImageBitmap(bitmap);
            /**
             * 当选择的图片不为空的话，在获取到图片的途径
             */
            File file = new File(logoPath);
            toUpImg(file);

//            localSelectPath = ImageCompress.compress(localSelectPath);
//
//            Log.d("localSelectPathImas", localSelectPath + "");
//            Bitmap bitmap = BitmapFactory.decodeFile(localSelectPath);
//
//            SPUtils.put(getApplication(),null,"personLogo",localSelectPath);
//            imgHead.setImageBitmap(bitmap);

//            HeadUrl.onImage(localSelectPath,imgHead);
            cameraPopupWindow.dismiss();
        } else if (requestCode == IMAGE_COMPLETE) {
//            UploadImage.getInstance().execute(localSelectPath, this);
            cameraPopupWindow.dismiss();
        }
    }

    public void showProgress(){

        mProgressDialog=new ProgressDialog(this);
        mProgressDialog.setMessage("正在上传中，请稍后...");
        mProgressDialog.show();
    }

    public String getSex(int sex){
       if (sex==0){
       return "女";
       }else if (sex==1){
        return "男";
       }
        return "男";
    }

    public int getStringSex(String sex){

        if (sex.equals("女")){
            return 0;
        }else if (sex.equals("男")){
            return 1;
        }
        return 3;
    }
    @Override
    public void update(Observable o, Object arg) {

        ResultEntity resultEntity = handlerError(arg);
        if (resultEntity!=null){

           if (resultEntity.getEventType() ==BranchAddressPresenter.By_UserProfile_update_success){
//               MAlert.alert("个人资料更新成功");
               PersonInfoActivity.this.finish();
           }else if (resultEntity.getEventType() ==BranchAddressPresenter.By_UserProfile_update_fail){

//               MAlert.alert("用户更新失败");
           }

        }
    }

    //选择性别
    public void showSexPop(){

        View inflate = LayoutInflater.from(this).inflate(R.layout.popwind_select_sex, null);
        sexPop=new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);

        sexPop.setAnimationStyle(R.style.popupwindow_anim_style);
        sexPop.setFocusable(true);
        final TextView manTv=inflate.findViewById(R.id.manTv);
        final TextView womanTv= inflate.findViewById(R.id.womanTv);
        final TextView callNumberTv=inflate.findViewById(R.id.callNumberTv);
        inflate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexPop.dismiss();
            }
        });
        //取消
        womanTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexEt.setText(womanTv.getText().toString());
                sexPop.dismiss();
            }
        });
        //呼叫
        manTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexEt.setText(manTv.getText().toString());
                sexPop.dismiss();
            }
        });
        inflate.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        inflate.setFocusableInTouchMode(true); //comment by
        sexPop.showAtLocation(inflate, Gravity.TOP,0,0);
    }



    /**
     * 根据图片的url路径获得Bitmap对象
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    public void toUpImg(File file){
        Map<String, String> params = new HashMap<String, String>();
        params.put("uid", uid);
        params.put("type", "avatar");
        params.put("md5","" );
        params.put("sha1", "");
        params.put("ori_name",file.getName());
        new UploadImageUtils().beginUpload(params, "by_image",file ,this);
        showProgress();
    }
    @Override
    public void uploadSuccess(UploadImageBean response) {
        MAlert.alert("上传成功");
        imgId=response.getData().getId()+"";
        SPUtils.put(MyApplication.instatnce, null,
                Const.HEAD, imgId);

        imgHead.setImageBitmap(returnBitmap(response.getData().getPrimary_file_uri()));

//        SPUtils.put(getApplication(),null,"personLogo",logoPath);
//        Glide.with(this)
//                .load(Const.DoctorImg + uid).into(imgHead);
        mProgressDialog.dismiss();
//        PersonBean bean=   new PersonBean();
//        bean.setHead(imgId);
//        bean.(bean);
    }

    @Override
    public void uploadFail(VolleyError error) {
//        MAlert.alert(error.toString());
        mProgressDialog.dismiss();
    }
}
